package com.wgf.controller;

import com.alibaba.cloud.ai.advisor.DocumentRetrievalAdvisor;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @auther zzyybs@126.com
 * @create 2025-08-01 16:51
 * @Description TODO
 */
@RestController
public class BailianRagController
{
    @Resource // 注入ChatClient，用于构建和发送聊天请求
    private ChatClient chatClient;
    @Resource// 注入DashScopeApi，用于构建文档检索器
    private DashScopeApi dashScopeApi;

    /**
     * http://localhost:6018/bailian/rag/chat
     * http://localhost:6018/bailian/rag/chat?msg=
     * @param msg
     * @return
     */
    @GetMapping("/bailian/rag/chat")
    public Flux<String> chat(@RequestParam(name = "msg",defaultValue = "如何退换货？") String msg)
    {
        //1 RetrieverOptions参数配置
        DashScopeDocumentRetrieverOptions documentRetrieverOptions = DashScopeDocumentRetrieverOptions.builder()
                .withIndexName("淘宝电商话术") // 设置知识库的名称
                .build();

        //2 百炼平台RAG知识库构建器,创建DashScopeDocumentRetriever实例，用于从指定的知识库中检索文档
        DocumentRetriever retriever = new DashScopeDocumentRetriever(dashScopeApi,documentRetrieverOptions);

        return chatClient.prompt()// // 使用ChatClient构建请求
                .user(msg)// 设置用户输入的消息
                .advisors(new DocumentRetrievalAdvisor(retriever))// 添加文档检索顾问，它会在生成回答前先检索相关文档，实现RAG功能
                .stream()// 以流式方式获取响应
                .content(); // 提取响应内容
    }

}
